<template>
  <div class="departments">
    <el-card>
      <template #header>
        <div>组织架构</div>
      </template>
      <div class="tree">
        <TreeItem :item="topInfo" style="margin-bottom: 20px" />
        <hr />
        <el-tree :data="list">
          <template v-slot="{ data }">
            <TreeItem style="width: 100%" :item="data" @getData="getData" />
          </template>
        </el-tree>
      </div>
    </el-card>
    <!-- 弹框组件 -->
    <DialogItem :init-list="initList" @getData="getData" />
  </div>
</template>

<script>
import { companyDepartment } from '@/api/departments'
import TreeItem from './components/tree-item.vue'
import DialogItem from './components/dialogItem.vue'
export default {
  components: {
    TreeItem,
    DialogItem
  },
  data () {
    return {
      topInfo: {
        name: '深圳黑马',
        manager: '负责人',
        isTop: true,
        // id值就是子部门的pid 用于验证新增同级部门是否重复
        id: ''
      },
      list: [],
      // 原始数组
      initList: []
    }
  },
  created () {
    this.getData()
  },
  methods: {
    async getData () {
      const res = await companyDepartment()
      this.topInfo.name = res.data.companyName
      this.initList = res.data.depts
      this.list = this.changeList(res.data.depts, '')
      console.log('组织架构', res)
    },
    changeList (arr, str) {
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.changeList(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  padding: 30px;
  .tree {
    width: 80%;
    padding: 30px 0;
    margin: 0 auto;
  }
}
</style>
